package com.atguigu.service;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.concurrent.TimeUnit;

@Service
@Transactional
@Slf4j
public class UserServiceImpl implements UserService{

    @Autowired
    public StringRedisTemplate stringRedisTemplate;

    @Override
    public int setLimitCount(String userId) {
        String limitKey = "LIMIT_"+userId;
        String limitNum = stringRedisTemplate.opsForValue().get(limitKey);
        int limit;
        if(limitNum==null){
            // 第一次调用
            stringRedisTemplate.opsForValue().set(limitKey,"1",1, TimeUnit.HOURS);
            limit = 1;
            return limit;
        }
        // 不是第一次调用
        limit=Integer.parseInt(limitNum)+1;
        stringRedisTemplate.opsForValue().set(limitKey,String.valueOf(limit),1, TimeUnit.HOURS);

        return limit;// 返回调用次数
    }

    @Override
    public boolean getLimitCount(String userId) {
        String limitKey = "LIMIT_"+userId;
        String limitNum = stringRedisTemplate.opsForValue().get(limitKey);

        if(limitNum==null){
            log.error("该用户没有访问申请次数，疑似异常~~!");
            return true; // 禁止访问
        }
        return Integer.parseInt(limitNum)>10;//大于10次就禁止访问
    }
}
